import json
import os


class Config:
    """Configuration class to manage application settings"""

    def __init__(self, config_file):
        """Initialize configuration from JSON file"""
        self.config_file = config_file
        self._load_config()
        # Create if the workspace or backup does not exist
        os.makedirs(self.backup_dir, exist_ok=True)

    def _load_config(self):
        """Load configuration from JSON file"""
        with open(self.config_file, "r", encoding="utf-8") as f:
            config = json.load(f)

        # Check required fields
        required_fields = [
            "workspace",
            "repo_uri",
            "source_dir",
            "dest_dir",
            "refresh_interval",
            "ssh_key",
        ]
        for field in required_fields:
            if field not in config:
                raise ValueError(f"Missing required field in config: {field}")

        self.workspace = config["workspace"]
        self.repo_uri = config["repo_uri"]
        self.source_dir = config["source_dir"]
        self.dest_dir = config["dest_dir"]
        self.refresh_interval = config["refresh_interval"]
        self.ssh_key = config["ssh_key"]
        self.backup_dir = os.path.join(self.workspace, "backup")

    def get_repo_name(self):
        """Extract repository name from repo URI"""
        return self.repo_uri.split("/")[-1].replace(".git", "")

    def get_local_repo_path(self):
        """Get local repository path"""
        return os.path.join(self.workspace, self.get_repo_name())

    def get_source_path(self):
        """Get source path within the repository"""
        return os.path.join(self.get_local_repo_path(), self.source_dir)
